package elitech.vietnam.weatherfashion.notification;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager.LayoutParams;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.readystatesoftware.viewbadger.BadgeView;

import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.Notification;
import elitech.vietnam.weatherfashion.notification.NotificationEndlessListView.EndlessListener;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;

public class NotificationPopupWindow extends PopupWindow implements EndlessListener {

	Context mContext;
	NotificationEndlessListView mListView;
	TextView mTextView;
	ProgressBar mProgress;
	NotificationArrayAdapter mAdapter;
	View anchor = null;
	BadgeView mBadge;
	int mUnreadCount = 0;
	
	public NotificationPopupWindow(Context context) {
		super(context);
		mContext = context;
		
		setContentView(LayoutInflater.from(context).inflate(R.layout.notification_window, null));
		mListView = (NotificationEndlessListView) getContentView().findViewById(R.id.notiListview);
		mTextView = (TextView) getContentView().findViewById(R.id.notiTextNoData);
		mProgress = (ProgressBar) getContentView().findViewById(R.id.notiProgress);
		
		mListView.setLoadingView(R.layout.layout_loadmore);
		mAdapter = new NotificationArrayAdapter(mContext, R.layout.notification_list_item, 0, WFApplication.getInstance().mListNoti);
		mListView.setAdapter(mAdapter);
		mListView.setListener(this);
		mListView.setOnItemClickListener(mAdapter);
		
		if (mAdapter.getCount() > 0)
			setLoading(false);
		if (mAdapter.getCount() < Const.NOTIFICATION_PER_LOAD)
			endOfList();
		
//		setOutsideTouchable(true);
		setFocusable(true);

		setWidth(LayoutParams.WRAP_CONTENT);
		setHeight(LayoutParams.WRAP_CONTENT);
	}
	
	public void show() {
		if (anchor == null)
			throw new IllegalArgumentException("Must call setViewAnchor first");
		showAsDropDown(anchor);
		mAdapter.notifyDataSetChanged();
		if (WFApplication.getInstance().mListNoti.size() > 0) {
//			setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
//			mListView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
//			setWidth(mListView.getMeasuredWidth());

		} else {
			MemberDTO mem = GlobalValue.getInstance(mContext).readUserInfo();
			new GetNotifications().execute(mem.getId());
		}
	}
	
	class GetNotifications extends AsyncTask<Integer, Integer, Boolean> {
		List<Notification> rs;
		@Override
		protected Boolean doInBackground(Integer... params) {
			PHPSoapServiceCaller service = new PHPSoapServiceCaller();
			int memID = params[0];
			try {
				rs = service.getNotificationUser(memID, WFApplication.getInstance().mListNoti.size(), Const.NOTIFICATION_PER_LOAD);
			} catch (IOException e) {
				e.printStackTrace();
				rs = new ArrayList<Notification>();
			}
			return null;
		}
		@Override
		protected void onPreExecute() {
			mListView.loadMore(true);
		}
		@Override
		protected void onPostExecute(Boolean result) {
			mListView.loadMore(false);
			WFApplication.getInstance().mListNoti.addAll(rs);
			mAdapter.notifyDataSetChanged();
			try {
				updateBadge();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}
			if (rs.size() < Const.NOTIFICATION_PER_LOAD)
				endOfList();
		}
	}
	
	public void setViewAnchor(View view) {
		this.anchor = view;
		this.mBadge = new BadgeView(mContext, anchor);
		updateBadge();
	}
	
	public void setLoading(boolean loading) {
		if (loading) {
			mProgress.setVisibility(View.VISIBLE);
			mTextView.setVisibility(View.GONE);
			mListView.setVisibility(View.GONE);
			return;
		}
		if (WFApplication.getInstance().mListNoti.size() <= 0) {
			mProgress.setVisibility(View.GONE);
			mTextView.setVisibility(View.VISIBLE);
			mListView.setVisibility(View.GONE);
			return;
		}
		mProgress.setVisibility(View.GONE);
		mTextView.setVisibility(View.GONE);
		mListView.setVisibility(View.VISIBLE);
		mAdapter.notifyDataSetChanged();
		try {
			updateBadge();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
	}

	public void updateBadge() {
		if (anchor == null)
			throw new IllegalArgumentException("Must call setViewAnchor first");
		mUnreadCount = 0;
		for (Notification noti : WFApplication.getInstance().mListNoti) {
			if (noti.Unread())
				mUnreadCount += 1;
		}
		mBadge.setText(mUnreadCount + "");
		if (mUnreadCount > 0)
			mBadge.show();
		else
			mBadge.hide();
	}
	
//	public Handler mHandler = new Handler(new Handler.Callback() {
//		@Override
//		public boolean handleMessage(Message msg) {
//			switch (msg.what) {
//			case 1:
//				try {
//					updateBadge();
//				} catch (IllegalArgumentException e) {
//					e.printStackTrace();
//				}
//				break;
//			default:
//				break;
//			}
//			return false;
//		}
//	});
	
	public int getUnreadCount() {
		return mUnreadCount;
	}
	
	public void setUnreadCount(int unread) {
		mUnreadCount = unread;
		mBadge.setText(mUnreadCount + "");
		if (mUnreadCount > 0)
			mBadge.show();
		else
			mBadge.hide();
	}

	@Override
	public void loadData() {
		MemberDTO mem = GlobalValue.getInstance(mContext).readUserInfo();
		new GetNotifications().execute(mem.getId());
	}
	
	public void endOfList() {
		mListView.endOfList();
	}
}
